<template>
  <div v-loading="loading" class="gl_contentBox gl_heightFull">
    <el-form ref="form" :model="form" size="mini" style="width: 460px" label-position="right" label-width="100px">
      <el-form-item prop="phoneNumber" label="服务电话">
        <el-input v-model="form.phoneNumber" placeholder="请输入" size="mini" />
      </el-form-item>
      <el-form-item prop="name" label="机构名称">
        <el-input v-model="form.name" placeholder="请输入" size="mini" />
      </el-form-item>
      <el-form-item prop="logoUrl" label="LOGO">
        <el-input v-show="false" v-model.trim="form.logoUrl" />
        <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
          <photo-cropper ref="photoCropper" :photograph="false" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
        </el-dialog>
        <div v-if="form.logoUrl" class="logo" @click="openPhotoCropper()">
          <img :src="getStaticFileUrl(form.logoUrl)" alt="">
          <div class="update_bg">更换</div>
        </div>
        <div v-else class="logo" @click="openPhotoCropper()">
          <i class="el-icon-plus upload" />
        </div>
      </el-form-item>
      <el-form-item prop="address" label="机构位置">
        <el-input v-model="form.address" placeholder="请输入" size="mini" />
        <div class="gl_mt_15">
          <span>经度：</span>
          <div class="gl_dis_ib gl_middle" style="width:130px">
            <el-input v-model="form.longitude" placeholder="请输入" size="mini" />
          </div>
          <span class="gl_pl_15">纬度：</span>
          <div class="gl_dis_ib gl_middle" style="width:130px">
            <el-input v-model="form.latitude" placeholder="请输入" size="mini" />
          </div>
        </div>
        <div class="gl_mt_5" style="text-align: right">
          <a class="amap_link" @click="toBaidu">百度地图拾取坐标系统</a>
        </div>
      </el-form-item>
      <!-- <div>
        <el-amap
          vid="amap-vue"
          :center="form.lnglat"
          :amap-manager="amapManager"
          :zoom="zoom"
          :events="events"
          style="height: 300px"
        >
          <el-amap-marker ref="marker" vid="component-marker" :position="form.lnglat" />
        </el-amap>
      </div> -->
    </el-form>
    <div class="gl_mt_20 btn_box">
      <el-button :loading="buLoading" type="primary" size="mini" @click="submit()">保存</el-button>
    </div>
  </div>
</template>

<script>
import photoCropper from '@/components/PhotoCropper';
import {
  api_POST_ClubSetting, // 新增
  api_GET_ClubSettingCurrent, // 获取
  api_PUT_ClubSettingCurrent // 更新
} from '@/extend/api/hallswaggerApi/app.js';
import {
  CreateSettingInput
} from '@/lib/form/hall/swaggerForm.js';
import { CopyData } from '@/lib/index';
import { getToken } from '@/lib/auth';
import axios from 'axios';
// import { AMapManager } from 'vue-amap';
// const amapManager = new AMapManager();
export default {
  components: {
    photoCropper
  },
  data() {
    return {
      photoCropperVisible: false,
      photoCropperOption: {
        img: '',
        autoCropWidth: '200px',
        autoCropHeight: '200px',
        enlarge: 1,
        fixedNumber: [200, 200]
      },
      loading: false,
      buLoading: false,
      isNew: false,
      id: '',
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      tokenInfo: getToken(),
      file: '',
      form: new CreateSettingInput()
      // form: {
      //   phone: '',
      //   name: '',
      //   address: '',
      //   lng: '', // 经度
      //   lat: '' // 纬度
      //   // lnglat: [116.397451, 39.909187] // 天安门
      // }
      // zoom: 12,
      // plugin: [ // 一些工具插件
      //   {
      //     // 定位需要得到浏览器允许，且定位可能会不准
      //     pName: 'Geolocation', // 定位
      //     events: {
      //       init(o) {
      //         // o 是高德地图定位插件实例
      //         o.getCurrentPosition((status, result) => {
      //           if (result && result.position) {
      //             this.form.lng = result.position.lng; // 设置经度
      //             this.form.lat = result.position.lat; // 设置维度
      //             this.form.lnglat = [this.lng, this.lat]; // 设置坐标
      //             this.$nextTick(); // 页面渲染好后
      //           }
      //         });
      //       }
      //     }
      //   }
      // ],
      // amapManager,
      // events: {
      //   click: (e) => {
      //     this.form.lng = e.lnglat.lng;
      //     this.form.lat = e.lnglat.lat;
      //     this.form.lnglat = [e.lnglat.lng, e.lnglat.lat];
      //     this.getFormattedAddress();
      //   }
      // }
    };
  },
  // mounted() {
  //   this.initMapByInput();
  // },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      var that = this;
      that.loading = true;
      api_GET_ClubSettingCurrent().then(res => {
        if (res) {
          CopyData(res, that.form);
          that.form.longitude = that.form.longitude || '';
          that.form.latitude = that.form.latitude || '';
          that.isNew = false;
        } else {
          that.isNew = true;
        }
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 去往百度坐标
    toBaidu() {
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = `https://api.map.baidu.com/lbsapi/getpoint/index.html`;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 上传图片限制
    check(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG或者PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    // 上传之前
    beforeUpload(file) {
      const checkData = this.check(file);
      if (checkData) {
        this.file = file;
      } else {
        return false;
      }
    },
    // 上传图片
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) reject(new Error());
        const form = new FormData();
        form.append('formFile', this.file);
        this.uploadApi(this.action, form).then(res => {
          if (res.status === 200) {
            this.form.logoUrl = res.data.tempUrl;
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    // 上传图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    submit() {
      var that = this;
      that.buLoading = true;
      if (that.isNew) {
        // 新增
        api_POST_ClubSetting(that.form).then(res => {
          if (res) {
            that.$message({ type: 'success', message: '操作成功' });
            that.getData();
          }
          that.buLoading = false;
        }).catch(error => {
          that.buLoading = false;
          that.$message({ type: 'error', message: error.error.message });
        });
      } else {
        // 更新
        api_PUT_ClubSettingCurrent(that.form).then(res => {
          if (res) {
            that.$message({ type: 'success', message: '操作成功' });
            that.getData();
          }
          that.buLoading = false;
        }).catch(error => {
          that.buLoading = false;
          that.$message({ type: 'error', message: error.error.message });
        });
      }
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper () {
      if (this.form['logoUrl']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticFileUrl(this.form['logoUrl']));
      }
      this.photoCropperVisible = true;
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.form, 'logoUrl', res.tempUrl);
        this.photoCropperVisible = false;
      });
    }
    // getFormattedAddress() {
    //   AMap.plugin('AMap.Geocoder', () => {
    //     const GeocoderOptions = {
    //       city: '全国'
    //     };
    //     const geocoder = new AMap.Geocoder(GeocoderOptions);
    //     geocoder.getAddress(this.form.lnglat, (status, result) => {
    //       console.log('通过经纬度拿到的地址', result);
    //       if (status === 'complete' && result.info === 'OK') {
    //         this.form.address = result.regeocode.formattedAddress;
    //       } else {
    //         this.form.address = '无法获取地址';
    //       }
    //     });
    //   });
    // },
    // initMapByInput() {
    //   AMap.plugin('AMap.Autocomplete', () => {
    //     const autoOptions = {
    //       city: '全国',
    //       input: 'tipinput'
    //     };
    //     const autoComplete = new AMap.Autocomplete(autoOptions);
    //     AMap.event.addListener(autoComplete, 'select', (e) => {
    //       console.log('通过输入拿到的地址', e);
    //       this.form.lat = e.poi.location.lat;
    //       this.form.lng = e.poi.location.lng;
    //       this.form.lnglat = [e.poi.location.lng, e.poi.location.lat];
    //       this.getFormattedAddress();
    //     });
    //   });
    // }
  }
};
</script>

<style scoped>
.btn_box {
  width: 460px;
  text-align: center;
}
.amap_link {
  color: #1890ff;
}
.amap_link:focus, .amap_link:hover {
  text-decoration: underline;
}
.logo {
  width: 100px;
	height: 100px;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid #f3f3f3;
  position: relative;
}
.update_bg {
  color: #fff;
  background-color: rgba(0,0,0,.5);
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
.logo:hover .update_bg{
  display: block;
  transition: opacity .3s;
}
.upload {
	width: 100px;
	height: 100px;
	cursor: pointer;
  border-radius: 50%;
	display: inline-block;
	border-radius: 10px;
	text-align: center;
	line-height: 100px;
}
img {
	width: 100%;
	height: 100%;
}
</style>
